package com.sc.highspeed.websocket;

import com.sc.highspeed.controller.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Admin on 2017/12/9.
 */
@Component
@Slf4j
public class WebSocketEndPoint implements WebSocketHandler {
    public static final Map<String, WebSocketSession> clientSocketSessionMap = new HashMap<String, WebSocketSession>();
    private static final String CLIENT_ID = "clientId";

    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {

        String clientId = (String) webSocketSession.getHandshakeAttributes().get(CLIENT_ID);
        System.out.println(clientId + "连接建立成功！");

        //添加客户端WebSocketSession
        if (clientSocketSessionMap.get(clientId) == null) {
            clientSocketSessionMap.put(clientId, webSocketSession);
        }

//        webSocketSession.sendMessage(new TextMessage("与服务器成功建立WebSocket连接！"));


    }

    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        
    }

    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if (webSocketSession.isOpen()) {
            webSocketSession.close();
        }

        Iterator<Map.Entry<String, WebSocketSession>> iterator = clientSocketSessionMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, WebSocketSession> entry = iterator.next();
            if (entry.getValue().getId().equals(webSocketSession.getId())) {
                clientSocketSessionMap.remove(entry.getKey());
//                log.info("Transport Error!" + entry.getKey() + "该会话已移除！");
                System.out.println("Transport Error!" + entry.getKey() + "该会话已移除！");
                break;
            }
        }

    }

    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        log.info("WebSocket:" + webSocketSession.getId() + "已关闭！");
        Iterator<Map.Entry<String, WebSocketSession>> iterator = clientSocketSessionMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, WebSocketSession> entry = iterator.next();
            if (entry.getValue().getId().equals(webSocketSession.getId())) {
                clientSocketSessionMap.remove(entry.getKey());
//                log.info("Connection Closed!" + entry.getKey() + "该会话已移除！");
                System.out.println("Connection Closed!" + entry.getKey() + "该会话已移除！");
                break;
            }
        }

    }

    public boolean supportsPartialMessages() {
        return false;
    }


    public void sendMessageToAllClient(TextMessage message) {
        Iterator<Map.Entry<String, WebSocketSession>> iterator = clientSocketSessionMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, WebSocketSession> entry = iterator.next();
            if (entry.getValue().isOpen()) {
                try {
                    entry.getValue().sendMessage(message);
                } catch (IOException e) {
//                    log.error("Send Error!" + entry.getValue().getId());
                    System.out.println("Send Error!" + entry.getValue().getId());
                    e.printStackTrace();
                }
            }
        }

    }
}


